package com.sl.au.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.ErrorStatus;
import com.sl.au.service.ErrorStatusService;

@RestController
@RequestMapping(value = "/ui/errorStatus")
public class ErrorStatusController extends BaseController {

	
	@Autowired
	ErrorStatusService errorStatusService;
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		ModelAndView modelAndView = this.createLayoutView("errorStatus/errorStatusIndex");
		return modelAndView;
	}

	@RequestMapping(value = "getpage", method = RequestMethod.GET)
	public Map<String, Object> getPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		int count = 0;
		List<ErrorStatus> errorStatus = null;
		errorStatus = errorStatusService.getPage(start, length, key, "createTime", Sort.Direction.DESC);
		count = errorStatusService.getCount(key);
		map.put("data", errorStatus);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	///保存
	@RequestMapping(value = "save", method = RequestMethod.POST)
	public Map<String, Object> saveErrorStatus(HttpServletRequest request, @RequestBody ErrorStatus errorStatus) {
		Map<String, Object> map = new HashMap<String, Object>();
		ErrorStatus save = null;
		if(errorStatus.getId().equals("")) {
			save = new ErrorStatus();
		}else {
			save = errorStatusService.getRepository().getOne(errorStatus.getId());
		}
		save.setErrorStatus(errorStatus.getErrorStatus());
		save.setErrorStatusName(errorStatus.getErrorStatusName());
		errorStatusService.getRepository().save(save);
		map.put("code", 0);
		map.put("msg", "故障类型保存成功！");
		return map;
	}

	@RequestMapping(value = "delete/{id}", method = RequestMethod.POST)
	public Map<String, Object> saveErrorStatus(HttpServletRequest request,@PathVariable String id) {
		Map<String, Object> map = new HashMap<String, Object>();
		errorStatusService.getRepository().delete(id);
		map.put("code", 0);
		map.put("msg", "故障类型删除成功！");
		return map;
	}
}
